<?php

namespace app\api\controller;

use app\common\controller\Api;
use Exception;
use addons\epay\library\Service;
use think\Log;
use app\common\model\cars\Order;
use app\common\model\MoneyLog;
use app\common\model\Order as ModelOrder;
use app\common\model\ScoreLog;
use app\common\model\User;
use think\Db;

/**
 * 微信支付接口
 */
class Wechat extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = '*';
    /**
     * 支付成功回调
     */
    //微信回调
    public  function notify()
    {
        $data = file_get_contents('php://input');
        Log::write('验证支付：' . $data);
        // $data='{"id":"a548f63e-1439-5415-8fea-ff37f2bd680a","create_time":"2023-04-03T11:51:37+08:00","resource_type":"encrypt-resource","event_type":"TRANSACTION.SUCCESS","summary":"支付成功","resource":{"original_type":"transaction","algorithm":"AEAD_AES_256_GCM","ciphertext":"F2BI6Hv6KFoLE6tijL5wdTc4/MRBSNqJLN4xXp11Q2z1CuEuslrr6b6vFEG+ESCjJtPCelnhF25drVBX3evTQEcxLDnXX8VMkGyjAI8nxa82+c7oT6GaEaRfRqVbQ95YHEx2wAN41IqEYJf6Q9s7oYInpR/Jql1+FhT8kqsOoGLWahQS+KFKcIH6IJkJ/4ID3FO+dnANSU39oiTEuOzDJfsEBMSNDVd3f7MCUacremdIEvw7k9nOgV0+GVp4/dZETDAM9AI9/hRLhHNg3qkS9nCj8CkmptLajOK8FpRiYni3qi+KdaCICtmM4B9+TRVL9hEAYyh6+Uj+h2vBvsZSsjbhgPd7fASi/L4s9JGtcYplXNWN4E+SrzZy7sSpo25T7LPCqgB/nzRZuhrzoLJ/TWnfzsrbIC8j2s/hKJjkMkPXFH4tzSMxcwgxLPyE4HoqWRIxo5abLiibAcTHZXIE5IOcQt7ttMFGy3oxYNnNrj1wmWRp9KurdMGMi0aiZL981BQ9KXUVJDFfxseDz0f8QPuzozxCJmk7XZzCLyE7L0uk1Yo3aotnPAE2R+WtEDze9VjgMUsuMxQ5kuf4PQ==","associated_data":"transaction","nonce":"0ZwFkqABkbDo"}}';
        $data = json_decode($data, true);
        $nonceStr = $data['resource']['nonce'];
        $associatedData = $data['resource']['associated_data'];
        $ciphertext = $data['resource']['ciphertext'];
        $ciphertext = base64_decode($ciphertext);
        // php>7.1,为了使用这个扩展，你必须将extension=php_sodium.dll添加到php.ini
        if (function_exists('\sodium_crypto_aead_aes256gcm_is_available') && \sodium_crypto_aead_aes256gcm_is_available()) {
            // $APIv3_KEY就是在商户平台后端设置是APIv3秘钥
            $orderData = \sodium_crypto_aead_aes256gcm_decrypt($ciphertext, $associatedData, $nonceStr, 'VYDra4BPiAnezbPvAuUeEMtnZnimIuzM');
            Log::write('支付成功：' . $orderData);
            // $orderData ='{"mchid":"1635149963","appid":"wx1c2ddbc154bece77","out_trade_no":"XX202212081422119380","transaction_id":"4200001642202212085961916819","trade_type":"JSAPI","trade_state":"SUCCESS","trade_state_desc":"支付成功","bank_type":"OTHERS","attach":"order","success_time":"2022-12-08T14:22:21+08:00","payer":{"openid":"of5sB5sZ4gSQQM6wY6h6KQp1hiWA"},"amount":{"total":1,"payer_total":1,"currency":"CNY","payer_currency":"CNY"}}';
            $orderData = json_decode($orderData, true);

            if ($orderData['trade_state'] == 'SUCCESS') {
                $order_sn = $orderData['out_trade_no']; //商户订单号
                $transaction_id = $orderData['transaction_id']; //微信订单号
                $attach = $orderData['attach']; //微信订单号
                // 启动事务
                Db::startTrans();
                try {
                    /*业务处理*/
                    switch ($attach) {
                        case 'cart_order':
                            $order = Order::get(['sn' => $order_sn, 'paytime' => null]);
                            if (!$order) {
                                return true;
                            }
                            if ($order->status == 0) {
                                $order->save(['paytime' => time(), 'status' => '1', 'transaction_id' => $transaction_id]);
                            }
                            break;
                        case 'order':
                            $order = ModelOrder::get(['sn' => $order_sn, 'paytime' => null]);
                            if (!$order) {
                                return true;
                            }
                            if ($order->status == 0) {
                                ScoreLog::income($order->user_id, $order->total_points, 2, 200, $order->sn);
                                $user = User::get($order->user_id);
                                MoneyLog::subcommission($user, $order->pay_money, $order->sn);
                                $order->save(['paytime' => time(), 'status' => '1', 'transaction_id' => $transaction_id]);
                            }
                            break;
                    }
                    Db::commit();
                    //应答微信支付已处理该订单的通知
                    return;
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    Log::error($e->getMessage());
                    return $e->getMessage();
                }
            }
        }
    }
    //退款回调地址
    public static function refund_notify()
    {

        $notifiedData = file_get_contents('php://input');
        Log::write('验证退款：' . $notifiedData);
        // $notifiedData = '{"id":"01785df1-2670-5d3e-990a-37e1584c62e3","create_time":"2023-03-30T16:20:28+08:00","resource_type":"encrypt-resource","event_type":"REFUND.SUCCESS","summary":"退款成功","resource":{"original_type":"refund","algorithm":"AEAD_AES_256_GCM","ciphertext":"ftDRCZz0Ea/Dkv8SE0xs/yXbVkwKTLuwUQZWoGup7AYRIl2ixjCHBe8RrjIlmYmxmAvhSmOgojAmZtzPvYFQib7ZSeBUSQQbkhy3pKjyRZ8wPXM7skCVU8VUK4TpKFesW5k6pcPVBFlGoPQ/dAotMvZ/1i11JDmY+yc1FsMNaV1V+zQ7VDQMifRApqyDs6okS2DuQEPoSq1a7SJu9BLTVjqaIOeQoTfnfgBz9GD2p+exixw6TW9M8ot2cutrXikcW5uYuoVeALHfk0E8/U2fPcdsjwptxdyREU5DnOnvk2sovWLF8D9xkk0drqV4f4FsTfVspgXZWkMtL9AW6OoGx1rAwCikdbSLqgWiqmGudKF693hDbOrgr7gF2GY8JkVwKpb3PTWjz3fVXWTMyR6qL3AwRz6HPgyNR4xz5ytmkz3NKXmVAo2JlRX7o262A5C6cymEI8wfh+QiA3Im+RTPcwQw1sSA/sH7hsTdDBW2JwVGnw+fmyDKMweqzkQNYfixigE=","associated_data":"refund","nonce":"Ux8v3JPRtnAH"}}';
        $data = json_decode($notifiedData, true);

        $nonceStr = $data['resource']['nonce'];
        $associatedData = $data['resource']['associated_data'];
        $ciphertext = $data['resource']['ciphertext'];
        $ciphertext = base64_decode($ciphertext);
        //php>7.1,为了使用这个扩展，你必须将extension=php_sodium.dll添加到php.ini
        if (function_exists('\sodium_crypto_aead_aes256gcm_is_available') && \sodium_crypto_aead_aes256gcm_is_available()) {
            //$APIv3_KEY就是在商户平台后端设置是APIv3秘钥
            $orderData = \sodium_crypto_aead_aes256gcm_decrypt($ciphertext, $associatedData, $nonceStr, 'HVcnpalfopaSXbROX8DU5x9XlTw0VgMV');
            Log::write('退款成功：' . $orderData);

            $orderData = json_decode($orderData, true);
            if ($orderData['refund_status'] == 'SUCCESS') {
                $transaction_id = $orderData['transaction_id']; //退款单号
                $order_sn = $orderData['out_trade_no']; //商户订单号
                // 启动事务
                Db::startTrans();
                try {
                    $order = Info::where('sn', $order_sn)->find();
                    if (!$order) {
                        return true;
                    }
                    $orders = ServiceOrder::get($order['order_id'], ['escort', 'user']);

                    ServiceOrder::cancelOrder($orders, $transaction_id);

                    Db::commit();
                    //应答微信支付已处理该订单的通知
                    return;
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    Log::error($e->getMessage());
                    return $e->getMessage();
                }
            }
        }
    }
}
